package com.itheima;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

@WebServlet("/ServletFind")
public class ServletFind extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String realPath = getServletContext().getRealPath("/stu.txt");
        BufferedReader br = new BufferedReader(new FileReader(realPath));
        HashMap<String, Student> hm = new HashMap<>();
            String s;
            while ((s=br.readLine())!=null){
                String[] split = s.split(":");
                hm.put(split[0],new Student(split[0],split[1],split[2],Integer.parseInt(split[3])));
            }
            System.out.println(hm.size());
            if (hm.size()==0){
                response.getWriter().write("您还没有学生信息,请添加");
                response.setHeader("Refresh","2;URL=entry.jsp");
                return;
            }
            br.close();
            //将集合存入session域中
            request.getSession().setAttribute("stulist",hm);
            //转发
            request.getRequestDispatcher("findstu.jsp").forward(request,response);
    }
}
